package com.spring.security.core.annotation;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.spera.shopoa.util.ShopOaSessionUtil;

@Aspect
@Component
public class SpringOaUserPermission {
	
	@Pointcut("@annotation(com.spring.security.core.annotation.OaUserPermission)")
	public void oaUserPermission(){
	}
	
	@Around("oaUserPermission()")
	public Object aroundExec(ProceedingJoinPoint pjp) throws Throwable{
		MethodSignature ms=(MethodSignature) pjp.getSignature();
		Method method=ms.getMethod();
		
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();  
	    ServletRequestAttributes sra = (ServletRequestAttributes)ra;  
	    HttpServletRequest request = sra.getRequest();  
		boolean ret = ShopOaSessionUtil.checkOaPriv(request,ShopOaSessionUtil.APPPATH+method.getAnnotation(OaUserPermission.class).value());
		
		if (ret) {
			try {
				return (ModelAndView) pjp.proceed();
			} catch (Throwable e) {
				ModelAndView mav = new ModelAndView("404");
//				mav.getModel().put("error", e.getMessage());
				return mav;
			}
		} else {
			ModelAndView mav = new ModelAndView("401");
//			mav.getModel().put("error", "unauthorised");
			return mav;
		}
	}
}
